const { Service } = require('egg')
// const { tableToList } = require('../utils/tools');
const cheerio = require('cheerio')

const iconv = require('iconv-lite') // 导入iconv-lite模块

module.exports = class ExamService extends Service {
  /**
   * * 考试安排
   * @param {String} term 学期
   * @return {Array} *
   */
  async table(term) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/cssfjw/student/ksap.ksapb_date.jsp`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/ksap.ksapb.html?menucode=S20403',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      data: {
        // xqlbmc: '',
        // xnxqid: term,
        // xqlb: '',

        xn: '2022',
        xq: '1',
        title: '',
        xnxq: '20221',
        kslc: '2',
        menucode_current: 'S20403',
      },
      timeout: 10000,
    })
    // console.log('res.status', res.status);
    // console.log('res.data', res.data);
    const info = {}
    // console.log('gbkString', gbkString);
    if (res.status === 200) {
      try {
        const gbkString = iconv.decode(res.data, 'gbk')
        const $ = cheerio.load(gbkString)
        const dataList = [
          $('body div').text().replace(/\s/g, ''),
        ]
        return dataList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return info
  }
}
